<?php

namespace App\Http\Controllers\Client\Mine;

use App\Http\Controllers\ClientController;
use App\Models\Tools\AliOss;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MineController extends ClientController
{
    /**
     * 商家：我的详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $we_id = $this->we_id;

        try {
            // vip信息
            $vip = DB::table('laifei_vip as lv')
                ->leftJoin('lottery_users as lu', 'lv.we_id', '=', 'lu.we_id')
                ->where('lv.we_id', '=', $we_id)
                ->where('lv.end_time', '>', date('Y-m-d H:i:s'))
                ->where('lv.is_delete', '=', 0)
                ->orderByDesc('vip_id')
                ->select('lv.v_id', 'lv.we_id', 'lv.vip_id', 'lv.total_month', 'lv.continue_times', 'lv.start_time', 'lv.end_time', 'lv.created_at as first_start_time',
                    'lu.nickname', 'lu.headimgurl')
                ->get()
                ->map(function ($item) {
                    $item->end_date = date('Y年m月d日', strtotime($item->end_time));
                    return $item;
                })
                ->toArray();
            $vip = $vip[0] ?? [];


            // 查询已购的课程
            $course = DB::table('laifei_course as lc')
                ->leftJoin('laifei_sys_course as lsc', 'lc.course_id', '=', 'lsc.course_id')
                ->where('lc.we_id', '=', $we_id)
                ->where('lc.is_delete', '=', 0)
                ->orderByDesc('lc.c_id')
                ->select('lc.c_id', 'lc.course_id', 'lc.created_at as bought_at',
                    'lsc.title', 'lsc.subtitle', 'lsc.learning_num', 'lsc.title_img')
                ->get()
                ->map(function ($item) {
                    $item->title_img = AliOss::getUrl($item->title_img);
                    return $item;
                })
                ->toArray();


            // 查询所有店铺
            $shops = DB::table('shop')->where('we_id', '=', $this->we_id)->get()->toArray();
            $shops = json_decode(json_encode($shops), true);


            // 查询探店余量
            $explore = [];
            if(count($shops)){
                // 查询余量
                $explore = DB::table('explore_remaining as er')
                    ->leftJoin('explore_channel as ec', 'er.channel_id', '=', 'ec.channel_id')
                    ->where('er.we_id', '=', $we_id)
                    ->select('er.channel_id', 'er.remaining_times', 'ec.channel_name')
                    ->get()
                    ->toArray();
                $explore = json_decode(json_encode($explore), true);
                // 查询退款
                $refund = DB::table('explore_refund_apply')
                    ->where('we_id','=',$this->we_id)
                    ->where('finish','=',0)
                    ->get()
                    ->keyBy('channel_id')
                    ->toArray();
                $refund = json_decode(json_encode($refund), true);
                foreach($explore as &$remaining){
                    if(isset($refund[$remaining['channel_id']])){
                        $remaining['number'] = $refund[$remaining['channel_id']]['number'];
                        $remaining['refunded_number'] = $refund[$remaining['channel_id']]['refunded_number'];
                        $remaining['refunding_number'] = $refund[$remaining['channel_id']]['refunding_number'];
                        $remaining['return_number'] = $refund[$remaining['channel_id']]['return_number'];
                    }
                }
            }


            // 查询探店购买记录
            $channels = DB::table('explore_channel')
                ->select('channel_id','channel_name')
                ->get()
                ->mapWithKeys(function($item){
                    return [$item->channel_id=>$item->channel_name];
                })
                ->toArray();
            $channels = json_decode(json_encode($channels), true);
            $order_history = DB::table('laifei_orders')
                ->where('we_id', '=', $this->we_id)
                ->whereIn('type', [3, 4])
                ->where('status', '=', 1)
                ->select('type','outer_id', 'num', 'success_at')
                ->orderByDesc('success_at')
                ->get()
                ->map(function($item)use($channels){
                    if($item->type === 3){
                        $order = [
                            'detail' => '购买【'.$channels[$item->outer_id].'】探店服务【'.$item->num.'】次',
                            'success_at' => $item->success_at,
                        ];
                    } else {
                        $order = [
                            'detail' => '购买霸王餐【'.$item->num.'】次',
                            'success_at' => $item->success_at,
                        ];
                    }
                    return $order;
                });




            // 霸王餐
            // 查询是否已经设置霸王餐策略
            $goods = false; //
            $goods_permit = false; // 允许设置霸王餐
            if (count($shops)) {
                // 查询是否已经设置霸王餐活动策略
                $goods = DB::table('lottery_goods')->where('creator', '=', $this->we_id)->count();
                $goods = $goods && true;
                if($goods){
                    $goods_permit = true;
                } else {
                    // 没有已有的规则，查看是否有店铺在已开通服务的城市内
                    foreach($shops as $shop){
                        if(in_array($shop['city'],Data::$lotteryPermitCity)){
                            $goods_permit = true;
                            break;
                        }
                    }
                }
            }
            $goods_remaining = DB::table('lottery_remaining as lr')
                ->leftJoin('shop_type as st','lr.st_id','=','st.st_id')
                ->where('lr.we_id', '=', $this->we_id)
                ->select('lr.lr_id','lr.st_id','lr.remaining_times','lr.in_use_times','st.name')
                ->get()
                ->toArray();

            return $this->setReturnJson(0, 'success', [
                'vip' => $vip,
                'course' => $course,
                'shops' => $shops,
                'explore' => $explore, // 探店余量
                'goods' => $goods,
                'goods_permit' => $goods_permit,
                'remaining' => $goods_remaining,
                'order_history' => $order_history, // 购买记录
            ]);
        } catch (\Exception $e) {
            Log::error(MineController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '信息查询失败');
        }
    }

}
